<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>资源分享平台</title>
  <style>
    :root {
      --bg-color: #f2f4f6;
      --card-bg: #ffffff;
      --text-color: #333;
      --accent-color: #007aff;
      --accent-hover: #005fcc;
      --border-color: #e0e0e0;
      --breadcrumb-bg: #fafafa;
      --folder-color: #4cd6a1;
      --file-color: #7383ff;
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      background-color: var(--bg-color);
      color: var(--text-color);
      margin: 0;
      padding: 20px;
    }

    .container {
      max-width: 900px;
      margin: 0 auto;
      background: var(--card-bg);
      border-radius: 16px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
      padding: 24px;
    }

    h1 {
      font-size: 24px;
      margin-bottom: 16px;
    }

    .breadcrumb {
      background: var(--breadcrumb-bg);
      padding: 12px 16px;
      border-radius: 12px;
      margin-bottom: 20px;
      font-size: 14px;
    }

    .breadcrumb span {
      margin: 0 4px;
      color: #666;
    }

    .breadcrumb a {
      color: var(--accent-color);
      text-decoration: none;
      cursor: pointer;
    }

    .items {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .item {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      border-radius: 12px;
      border: 1px solid var(--border-color);
      background-color: #fbfbfb;
      cursor: pointer;
      transition: background-color 0.2s ease;
    }

    .item:hover {
      background-color: #f0f0f0;
    }

    .icon {
      margin-right: 12px;
      font-size: 20px;
      color: var(--folder-color);
    }

    .file .icon {
      color: var(--file-color);
    }

    .name {
      font-weight: 500;
    }

    /* 限流提示框 */
    #rateLimitToast {
      position: fixed;
      top: 20px;
      right: 20px;
      background-color: #ff4d4d;
      color: white;
      padding: 12px 20px;
      border-radius: 8px;
      font-size: 14px;
      z-index: 9999;
      opacity: 0;
      transform: translateY(-20px);
      transition: opacity 0.3s ease, transform 0.3s ease;
    }

    #rateLimitToast.show {
      opacity: 1;
      transform: translateY(0);
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>资源分享平台</h1>
    <div class="breadcrumb" id="breadcrumb">加载中...</div>
    <div class="items" id="items">加载中...</div>
  </div>

  <!-- 用于下载的隐藏元素 -->
  <a id="downloadLink" style="display: none;"></a>

  <!-- 限流提示框 -->
  <div id="rateLimitToast">下载频率过高，请稍后再试</div>

  <script>
    const breadcrumbEl = document.getElementById("breadcrumb");
    const itemsEl = document.getElementById("items");
    const downloadLink = document.getElementById("downloadLink");
    const toast = document.getElementById("rateLimitToast");

    let currentPath = "";

    function decodePath(path) {
      return decodeURIComponent(path);
    }

    function encodePath(path) {
      return encodeURIComponent(path);
    }

    function updateBreadcrumb(path) {
      const parts = path.split("/").filter(p => p !== "");
      const crumbs = [
        `<a onclick="goToBreadcrumb('')">🏠 首页</a>`
      ];
      let current = "";
      parts.forEach((part, index) => {
        current += (index === 0 ? part : `/${part}`);
        crumbs.push(`<span> / </span><a onclick="goToBreadcrumb('${encodePath(current)}')">${decodePath(part)}</a>`);
      });
      breadcrumbEl.innerHTML = crumbs.join("");
    }

    function goToBreadcrumb(path) {
      currentPath = path || "";
      updateUrl(currentPath); // 更新地址栏
      loadDirectory(path);
    }

    function updateUrl(path) {
      const newPath = path ? `?path=${encodePath(path)}` : '';
      window.history.pushState({ path }, '', window.location.pathname + newPath);
    }

    function showToast(message) {
      toast.textContent = message;
      toast.classList.add("show");
      setTimeout(() => {
        toast.classList.remove("show");
      }, 3000);
    }

    function handleDownload(filepath) {
      const encodedPath = encodePath(filepath);
      const filename = decodeURIComponent(filepath.split('/').pop());

      fetch(`/download/${encodedPath}`, { method: 'GET', headers: { 'X-Check-Limit': 'true' } })
        .then(response => {
          if (response.status === 429) {
            showToast("下载频率过高，请稍后再试");
            return;
          }

          if (!response.ok) {
            showToast("下载失败，文件可能不存在");
            return;
          }

          // 触发实际下载
          downloadLink.href = `/download/${encodedPath}`;
          downloadLink.download = filename;
          downloadLink.click();
        })
        .catch(err => {
          console.error("检查限流失败", err);
          showToast("网络异常，请稍后再试");
        });
    }

    function loadDirectory(path) {
      const encodedPath = encodePath(path);
      fetch(`/api/tree${encodedPath ? "?path=" + encodedPath : ""}`)
        .then(res => res.json())
        .then(data => {
          itemsEl.innerHTML = "";
          updateBreadcrumb(path);

          if (!data.children || data.children.length === 0) {
            itemsEl.innerHTML = "<p>当前目录为空</p>";
            return;
          }

          data.children.forEach(item => {
            const itemEl = document.createElement("div");
            itemEl.className = "item " + (item.type === "folder" ? "folder" : "file");

            const icon = document.createElement("div");
            icon.className = "icon";
            icon.textContent = item.type === "folder" ? "📁" : "📄";

            const name = document.createElement("div");
            name.className = "name";
            name.textContent = item.name;

            itemEl.appendChild(icon);
            itemEl.appendChild(name);

            if (item.type === "folder") {
              itemEl.addEventListener("click", () => {
                const newPath = path ? `${path}/${item.name}` : item.name;
                goToBreadcrumb(newPath);
              });
            } else {
              itemEl.addEventListener("click", () => {
                handleDownload(item.path); // 使用无刷新下载
              });
            }

            itemsEl.appendChild(itemEl);
          });
        })
        .catch(err => {
          console.error("获取目录失败", err);
          itemsEl.innerText = "加载目录失败";
        });
    }

    // 处理页面加载时的初始路径（支持分享链接）
    window.addEventListener('load', () => {
      const urlParams = new URLSearchParams(window.location.search);
      const path = urlParams.get('path') || '';
      currentPath = decodeURIComponent(path);
      updateUrl(currentPath);
      loadDirectory(currentPath);
    });

    // 支持浏览器后退/前进按钮
    window.addEventListener('popstate', (event) => {
      const path = event.state?.path || '';
      loadDirectory(path);
    });
  </script>
</body>

</html>